import React, { PureComponent } from 'react';
import axios from 'axios';
import { web3, walletListContract } from '../../../config';
import { Table, Button, Pagination, Dialog, Tag, Message } from '@alifd/next';
import IceContainer from '@icedesign/container';
import '@alifd/next/dist/next.css';

class WorkCheckTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = ({
      current: 1,
      isLoading: false,
      workCheckData: [],
      dialogVisible: false,
      dialogData: [],
      dialogTags: ""
    });
  }

  getWorkCheckData = () => {
    axios.get('http://localhost:9080/work/search/checking?start=0&length=10',{
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      console.log(res.data.data);
      this.setState({
        workCheckData: res.data.data
      })
    }).catch(()=>{
      console.log('error');
    })
  }

  onOpen = (_record) => {
    this.setState({
      dialogVisible: true,
      dialogData: _record,
      dialogTags: _record.tags
    });
  }

  onClose = () => {
    this.setState({
      dialogVisible: false
    });
  }

  onPass = async (_authorId, _workId, _workName) => {
    // 上链
    Message.show({
      type: 'loading',
      content: '作品上链中，请等待片刻'
    });
    const [adminWallet] = await web3.eth.getAccounts();
    console.log(adminWallet);
    let authorId = _authorId.toString();
    await walletListContract.methods.createWork(authorId, _workId, _workName).send({
      from: adminWallet
    });
    const workAddress = await walletListContract.methods.getLatestWorkAddress().call();
    console.log(workAddress);

    await axios.get('http://localhost:9080/work/update-admin?checked=1&workId='+_workId+'&certAddress='+workAddress, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      alert('操作完成！');
      this.setState({
        dialogVisible: false
      });
    }).catch(() => {
      alert('error');
    });
  }

  onReject = (_workId) => {
    axios.get('http://localhost:9080/work/update-admin?checked=-1&workId='+_workId, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      alert('操作完成！');
      this.setState({
        dialogVisible: false
      });
    }).catch(() => {
      alert('error');
    });
  }

  render() {
    const { workCheckData, isLoading, current, dialogData, dialogVisible, dialogTags } = this.state;
    console.log("workCheckData: ", workCheckData);
    return (
      <IceContainer title="作品列表">
        <Table loading={isLoading} dataSource={workCheckData}>
          <Table.Column 
            title="序号" 
            width={20} 
            cell={(item, index) => ++index + 10*(current-1)} 
          />
          <Table.Column title="作品名称"  dataIndex="workName" width={150} />
          <Table.Column title="作者姓名" dataIndex="authorName" width={150} />
          <Table.Column title="作品格式" dataIndex="workFormat" width={80} />
          <Table.Column title="作品类型" dataIndex="workType" width={80} />
          <Table.Column title="上传日期" dataIndex="createTime" width={100} />
          <Table.Column
            title="操作" 
            width={50}
            cell={(item, index, record) => {
              return (
                <Button onClick={() => this.onOpen(record)} type="primary">
                  审核
                </Button>
              )
            }}
          />
        </Table>
        <Pagination 
          style={styles.pagination}
          current={current}
          onChange={this.handlePaginationChange}
        />
        <Dialog
          title={"您正在审核"+dialogData.workName}
          visible={dialogVisible}
          onOk={this.onClose}
          onClose={this.onClose}
          onCancel={this.onClose}
          width={200}
          footer={
            <div>
               <Button type="secondary" style={{ color: '#336666', marginRight: '10px' }} onClick={() => this.onPass(dialogData.authorId, dialogData.workId, dialogData.workName)}>通过</Button>
               <Button warning type="secondary" style={{ color: 'red', marginRight: '10px' }} onClick={() => this.onReject(dialogData.workId)}>不通过</Button>
               <Button type="normal" onClick={this.onClose}>取消</Button>
            </div>
          }
        >
          <IceContainer>
            <div style={styles.infoRow}>
              <div style={styles.infoLabel}>作品ID</div>
              <div style={styles.infoDetail}>{dialogData.workId}</div>
            </div>
            <div style={styles.infoRow}>
              <div style={styles.infoLabel}>作品名称</div>
              <div style={styles.infoDetail}>{dialogData.workName}</div>
            </div>
            <div style={styles.infoRow}>
              <div style={styles.infoLabel}>作者姓名</div>
              <div style={styles.infoDetail}>{dialogData.authorName}</div>
            </div>
            <div style={styles.infoRow}>
              <div style={styles.infoLabel}>作品描述</div>
              <div style={styles.infoDetail}>{dialogData.workDesc}</div>
            </div>
            <div style={styles.infoRow}>
              <div style={styles.infoLabel}>上传时间</div>
              <div style={styles.infoDetail}>{dialogData.createTime}</div>
            </div>
            <div style={styles.infoRow}>
              <div style={styles.infoLabel}>作品类型</div>
              <div style={styles.infoDetail}>{dialogData.workType}</div>
            </div>
            <div style={styles.infoRow}>
              <div style={styles.infoLabel}>作品标签</div>
              <div style={styles.infoDetail}>
                {
                  dialogTags ?
                    dialogTags.split(",").map((tag, index) => {
                      return (
                        <Tag key={index} type="normal" size="small">{tag}</Tag>
                      );
                    })
                  : "无"
                }
              </div>
            </div>
          </IceContainer>
        </Dialog>
      </IceContainer>
    );
  }

  // 从后台获取数据 http://localhost:9080/work/search/checking?start=0&length=10
  componentDidMount() {
    this.getWorkCheckData();
  }
}

const styles = {
  status: {
    position: 'relative',
    paddingLeft: '20px',
  },
  dot: {
    width: '10px',
    height: '10px',
    position: 'absolute',
    left: '0',
    top: '2px',
    borderRadius: '50%',
  },
  largeWidth: {
    width: '80px',
  },
  pagination: {
    marginTop: '20px',
    textAlign: 'right',
  },
  infoRow: {
    padding: '16px 0',
    display: 'flex',
    borderBottom: '1px solid #f6f6f6',
  },
  infoLabel: {
    flex: '0 0 100px',
    color: '#999',
  },
  infoDetail: {
    width: '400px',
    height: 'auto',
  },
};

// const mapState = (state) => ({
//   current: state.WorkCheck.get('current'),
//   isLoading: state.WorkCheck.get('isLoading'),
//   workCheckData: state.WorkCheck.get('workCheckData').toJS(),
//   dialogVisible: state.WorkCheck.get('dialogVisible'),
//   dialogData: state.WorkCheck.get('dialogData').toJS(),
//   dialogTags: state.WorkCheck.get('dialogTags')
// });

// const mapDispatch = (dispatch) => ({
//   getWorkCheckData() {
//     dispatch(actionCreators.getWorkCheckData());
//   },
//   onOpen(record) {
//     dispatch(actionCreators.onOpen(record));
//   },
//   onClose() {
//     dispatch(actionCreators.onClose());
//   },
//   onPass(_authorId, _workId, _workName) {
//     dispatch(actionCreators.onPass(_authorId, _workId, _workName));
//   },
//   onReject(workId) {
//     dispatch(actionCreators.onReject(workId));
//   }
// });

export default WorkCheckTable;